<script setup lang="ts">
import { ref } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRolePage } from "./utils/hook";

import Plus from "~icons/ep/plus";
import EditPen from "~icons/ep/edit";
import Delete from "~icons/ep/delete";
import Menu from "~icons/ri/admin-line";

defineOptions({ name: "UserRoles" });

const tableRef = ref();

const {
  filterForm,
  statusOptions,
  scopeOptions,
  pagination,
  tableData,
  columns,
  loading,
  handleSearch,
  handleResetFilters,
  handlePageChange,
  handleSizeChange,
  roleDialogVisible,
  roleDialogTitle,
  roleForm,
  roleFormRef,
  roleRules,
  roleSaving,
  openCreate,
  openEdit,
  submitRole,
  handleDelete,
  permissionDialogVisible,
  permissionOptions,
  permissionLoading,
  permissionSaving,
  selectedPermissionIds,
  openPermissionDialog,
  savePermissions
} = useRolePage();
</script>

<template>
  <div class="roles-page">
    <el-form
      :inline="true"
      :model="filterForm"
      class="search-form bg-bg_color w-full pl-4 pt-3 pb-2 overflow-auto"
    >
      <el-form-item label="关键词：" prop="keyword">
        <el-input
          v-model="filterForm.keyword"
          placeholder="角色名称 / 标识"
          clearable
          class="w-[220px]!"
        />
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="filterForm.status"
          placeholder="全部状态"
          clearable
          class="w-[160px]!"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="范围：" prop="scope_type">
        <el-select
          v-model="filterForm.scope_type"
          placeholder="全部范围"
          clearable
          class="w-[160px]!"
        >
          <el-option label="全部范围" value="" />
          <el-option
            v-for="item in scopeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon('ep:refresh')"
          @click="handleResetFilters"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      title="角色管理"
      :columns="columns"
      :tableRef="tableRef"
      @refresh="handleSearch"
      @fullscreen="tableRef.value?.setAdaptive?.()"
    >
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(Plus)"
          @click="openCreate"
        >
          新增角色
        </el-button>
      </template>

      <template #default="{ size, dynamicColumns }">
        <template v-if="loading && tableData.length === 0">
          <el-skeleton :rows="10" animated />
        </template>
        <template v-else>
          <PureTable
            ref="tableRef"
            v-loading="loading"
            :columns="dynamicColumns"
            :data="tableData"
            :size="size"
            :pagination="pagination"
            @page-current-change="handlePageChange"
            @page-size-change="handleSizeChange"
          >
            <template #permissionCount="{ row }">
              <el-tag type="info" size="small" effect="plain">
                {{ row.permission_ids?.length ?? 0 }}
              </el-tag>
            </template>
            <template #status="{ row }">
              <el-tag
                :type="row.status === 1 ? 'success' : 'danger'"
                size="small"
                effect="plain"
              >
                {{ row.status === 1 ? "已启用" : "已停用" }}
              </el-tag>
            </template>
            <template #operation="{ row, size }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :icon="useRenderIcon(EditPen)"
                :size="size"
                @click="openEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                class="reset-margin"
                link
                type="primary"
                :icon="useRenderIcon(Menu)"
                :size="size"
                @click="openPermissionDialog(row)"
              >
                权限
              </el-button>
              <el-popconfirm
                :title="`确认删除角色「${row.name}」吗？`"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="danger"
                    :icon="useRenderIcon(Delete)"
                    :size="size"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </PureTable>
        </template>
      </template>
    </PureTableBar>

    <el-dialog
      v-model="roleDialogVisible"
      :title="roleDialogTitle"
      width="480px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="例如：运营管理员"
            maxlength="40"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色标识" prop="slug">
          <el-input
            v-model="roleForm.slug"
            placeholder="operation-admin"
            maxlength="40"
            show-word-limit
            :disabled="roleForm.id !== 0"
          />
        </el-form-item>
        <el-form-item label="角色范围" prop="scope_type">
          <el-select v-model="roleForm.scope_type" placeholder="请选择范围">
            <el-option
              v-for="item in scopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="roleForm.status"
            :inactive-value="0"
            :active-value="1"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            maxlength="200"
            show-word-limit
            placeholder="说明角色职责、权限范围，便于运维管理"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="roleSaving" @click="submitRole">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="permissionDialogVisible"
      title="配置权限"
      width="560px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-transfer
        v-model="selectedPermissionIds"
        :data="permissionOptions"
        filterable
        filter-placeholder="搜索权限名称或标识"
        :titles="['全部权限', '已选择']"
        :props="{ key: 'key', label: 'label' }"
        :loading="permissionLoading"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="permissionSaving"
            @click="savePermissions"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.roles-page {
  padding: 12px 12px 20px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.search-form :deep(.el-form-item__label) {
  padding-right: 6px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
